<script lang="ts" setup>
import type {FormInstance, FormRules, UploadInstance, UploadRawFile} from 'element-plus';
import * as materialApi from "@/api/business/material";
import {DICT_TYPE, getDictOptions} from "@/utils/dict";
import type {UploadProps, UploadUserFile} from 'element-plus'
import {genFileId} from 'element-plus'

defineOptions({name: "MaterialForm"})
const message = useMessage()
const {t} = useI18n()
const emit = defineEmits(['success'])

const disabled = computed(() => {
  return type.value === 'detail'
})
const type = ref('detail')
const title = ref('详情')
const dialogVisible = ref(false)
const formLoading = ref(false)


const formRef = useTemplateRef<FormInstance>('formRef')
const form = ref({
  productName: void 0,
  imgUrl: void 0,
  unit: void 0,
  remark: void 0,
  other: void 0,
})
const rules = ref<FormRules>({
  productName: [
    {required: true, message: '请输入商品名称', trigger: 'blur'},
  ],
  unit: [
    {required: true, message: '请选择单位', trigger: 'change'},
  ],
  remark: [
    {required: true, message: '请输入备注', trigger: 'blur'},
  ],
  other: [
    {required: true, message: '请输入其他信息', trigger: 'blur'},
  ],
})

function handleClose() {
  dialogVisible.value = false
  formRef.value?.resetFields()
  uploadRef.value?.clearFiles()
  form.value = {
    productName: void 0,
    imgUrl: void 0,
    unit: void 0,
    remark: void 0,
    other: void 0,
  }
}

async function open(state: 'add' | 'edit' | 'detail' = "detail", id?: string) {
  type.value = state
  title.value = t('action.' + state)
  dialogVisible.value = true
  if (id) {
    formLoading.value = true
    try {
      form.value = await materialApi.getMaterial(id)
    } finally {
      formLoading.value = false
    }
  }
}

async function handleSubmit() {
  try {
    await formRef.value?.validate()
    if (type.value === 'add') {
      await materialApi.createMaterial(form.value)
      message.success(t('common.createSuccess'))
    } else if (type.value === 'edit') {
      await materialApi.updateMaterial(form.value)
      message.success(t('common.updateSuccess'))
    }
    console.log(form.value.imgUrl)
    emit('success')
    handleClose()
  } catch (e) {
    console.log(e)
  }
}


const previewVisible = ref(false)
const dialogImageUrl = ref('')
const imgType = ref(['image/png', 'image/jpeg'])
const uploadRef = useTemplateRef<UploadInstance>(`uploadRef`)

const beforeUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (!imgType.value.includes(rawFile.type)) {
    ElMessage.error('文件格式必须是png、jpg、jpeg')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过 2MB!')
    return false
  }
  return true
}
const uploadImg = (options) => {
  // return Promise.reject()
  console.log(options, 11111111)
  form.value.imgUrl = `https://p0.itc.cn/q_70/images03/20210306/b171f2818bd5480aa77cac01000cd5fc.jpeg`
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  previewVisible.value = true
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}
defineExpose({
  open
})
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :title
    top="5vh"
    width="50%"
    @close="handleClose"
  >
    <el-form ref="formRef" v-loading="formLoading" :inline="true" :model="form"
             :rules class="-mb-15px" label-width="auto">
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item class="w-100%" label="商品名称" prop="productName">
            <el-input v-model="form.productName" :disabled clearable placeholder="请输入商品名称"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="w-100%" label="单位" prop="unit">
            <el-select v-model="form.unit" :disabled clearable
                       placeholder="请选择商品单位">
              <el-option v-for="item in getDictOptions(DICT_TYPE.BUSINESS_UNIT)"
                         :key="item.value" :label="item.label"
                         :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="w-100%" label="备注" prop="remark">
            <el-input v-model="form.remark" :disabled clearable placeholder="请输入备注"
                      type="textarea"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item class="w-100%" label="其他" prop="other">
            <el-input v-model="form.other" :disabled clearable placeholder="请输入其他信息"
                      type="textarea"/>
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item class="w-100%" label="图片" prop="imgUrl">
            <el-upload
              ref="uploadRef"
              :accept="imgType.join(',')"
              :before-upload="beforeUpload"
              :disabled
              :http-request="uploadImg"
              :limit="1"
              :on-exceed="handleExceed"
              :on-preview="handlePictureCardPreview"
              action
              drag
              list-type="picture-card"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button v-show="type!=='detail'" type="primary" @click="handleSubmit">
          确定
        </el-button>
      </div>
    </template>

    <el-dialog v-model="previewVisible">
      <img :src="dialogImageUrl" alt="图片预览" class="w-full"/>
    </el-dialog>
  </el-dialog>
</template>

<style lang="scss" scoped>
:deep(.el-upload-dragger) {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
